<?php
namespace app\api\controller;

use app\common\model as M;

/**
 * 客户模块
 */
class Customer extends \app\api\ApiAuth
{
    public $model = '\app\common\model\User';
	
    /**
     * 客户明细列表
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
	public function customers()
	{
        $customers = [];
        $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
        if ( $sales_admin_id > 0 ) {
            $filter = input();
            $filter['sales_admin_id'] = $sales_admin_id;
            $users = $this->model::getList($filter);
            if ( isset($users['data']) ) {
                $customers = $users['data'];
            }
        }
		return $this->returnSuccess($customers);
	}

    /**
     * 客户信息明细
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     * uid: 0,
    usn: '',
    full_name: '',
    nickname: '',
    mobile: '',
    tour_perfer: '',
    cus_from: '',
    wheregone: '',
    tour_target: '',
    remark: '',
    register_date: '',
    last_time: '',
    birthday: '',
    last_processon_time: '',
    is_idcheck: 0,
    realname: '',
    idnumber: '',
    address: '',
    check_time: '',
    order_nums: 0,
    order_amt: 0
     */
    public function info(int $uid)
    {
        $info = M\User::alias('u')->field("u.uid,u.usn,u.full_name,u.nickname,u.mobile,u.mate_mobile,u.mate_mobile2,u.tour_perfer,u.cus_from,u.wheregone,u.tour_target,u.remark,u.register_date,u.last_time,u.birthday,u.last_processon_time,u.is_idcheck,ifnull(idc.realname,'未实名') as realname,ifnull(idc.idnumber,'暂无') as idnumber,ifnull(idc.address,'暂无') as address,ifnull(idc.check_time,'暂无') as check_time,0 as order_nums,0 as order_amt")
        ->join('__USER_IDCARD__ idc','u.uid=idc.uid','LEFT')
        ->where('u.uid',$uid)
        ->find();

        $info->order_nums = M\Order::where('pay_status',1)->where('uid',$uid)->count();
        $info->order_amt = M\Order::where('pay_status',1)->where('uid',$uid)->sum('order_amt');
        return $this->returnSuccess($info);
    }

    /**
     * 客户统计
     * @Author   FW
     * @DateTime 2024-03-21
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function statistic()
    {
        $statistic = [
            'yesPlus'       => 0, // 昨日新增
            'totalNums'     => 0, // 今日新增
            'todayVist'     => 0, // 今日登录（访问）
        ];
        ## 检查是否有权操作
        $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
        if ( $sales_admin_id > 0 ) {
            $statistic['yesPlus'] = $this->model::where('register_date','BETWEEN',[date('Y-m-d 00:00:00',strtotime('-1 days')),date('Y-m-d 00:00:00')])->where('sales_admin_id' , $sales_admin_id)->count();

            $statistic['totalNums'] = $this->model::where('sales_admin_id' , $sales_admin_id)->count();

            $statistic['todayVist'] = M\UserLoginRecords::alias('m')
            ->where('m.loginTime','BETWEEN',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])
            ->where(sprintf("m.uid IN (SELECT uid FROM `eb_user` WHERE sales_admin_id = %d)" , $sales_admin_id))
            ->count();
        }

        return $this->returnSuccess($statistic);
    }

     /**
     * 销售统计
     * @Author   FW
     * @DateTime 2024-03-21
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function salesStatistic()
    {
        $statistic = [
            'yesOrderAmt'   => 0, // 昨日订单额
            'monthOrderAmt' => 0, // 本月订单额
            'totalOrderAmt' => 0, // 总订单额
        ];
        ## 检查是否有权操作
        $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
        if ( $sales_admin_id > 0 ) {
            $statistic['yesOrderAmt'] = M\Order::alias('m')
            ->where('create_time','BETWEEN',[date('Y-m-d 00:00:00',strtotime('-1 days')),date('Y-m-d 00:00:00')])
            ->where(sprintf("m.uid IN (SELECT uid FROM `eb_user` WHERE sales_admin_id = %d)" , $sales_admin_id))
            ->where('pay_status',1)
            ->sum('order_amt');

            $statistic['monthOrderAmt'] = M\Order::alias('m')
            ->where('create_time','BETWEEN',[date('Y-m-01 00:00:00'),date('Y-m-01 00:00:00',strtotime('+1 months'))])
            ->where(sprintf("m.uid IN (SELECT uid FROM `eb_user` WHERE sales_admin_id = %d)" , $sales_admin_id))
            ->where('pay_status',1)
            ->sum('order_amt');

            $statistic['totalOrderAmt'] = M\Order::alias('m')
            ->where(sprintf("m.uid IN (SELECT uid FROM `eb_user` WHERE sales_admin_id = %d)" , $sales_admin_id))
            ->where('pay_status',1)
            ->sum('order_amt');
        }

        return $this->returnSuccess($statistic);
    }

     /**
     * 销售明细列表
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function salesList()
    {
        $customers = [];
        $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
        if ( $sales_admin_id > 0 ) {
            $filter = input();
            $filter['sales_admin_id'] = $sales_admin_id;
            $users = $this->model::getList($filter);
            if ( isset($users['data']) ) {
                $customers = $users['data'];
            }
        }
        return $this->returnSuccess($customers);
    }

    /**
     * 标注信息保存
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function saveInfo()
    {
        $info = $this->request->post();
        if ( !empty($info) ) {
            ## 检查是否有权操作
            $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
            if ( $sales_admin_id > 0 ) {
                $cusUserAdminId = $this->model::where('uid',$info['uid'])->value('sales_admin_id');
                if ( $sales_admin_id != $cusUserAdminId ) return $this->returnFail('无权操作');

                $user = $this->model::where('uid',$info['uid'])->find();

                ## 检查是否已存在
                $mobile = $info['mobile'] ?? '';
                if ( !$mobile ) return $this->returnFail('手机号必填！');

                if ( $mobile && $mobile != $user->mobile ) {
                    $his = $this->model::where('mobile' , $mobile)->count();
                    if ( $his > 0 ) return $this->returnFail('手机号关联的客户已存在！');
                }

                $mate_mobile = $info['mate_mobile'] ?? '';
                if ( $mate_mobile && $mate_mobile != $user->mate_mobile ) {
                    ## 检查是否已存在
                    $his = $this->model::where('mate_mobile' , $mate_mobile)->whereOr('mate_mobile2' , $mate_mobile)->count();
                    if ( $his > 0 ) return $this->returnFail('亲属手机号关联的客户已存在！');
                }

                $mate_mobile2 = $info['mate_mobile2'] ?? '';
                if ( $mate_mobile2 && $mate_mobile2 != $user->mate_mobile2 ) {
                    ## 检查是否已存在
                    $his = $this->model::where('mate_mobile' , $mate_mobile2)->whereOr('mate_mobile2' , $mate_mobile2)->count();
                    if ( $his > 0 ) return $this->returnFail('亲属手机号关联的客户已存在！');
                }

                if ( $mate_mobile && $mate_mobile2 ) {
                    if ( $mate_mobile == $mate_mobile2 ) return $this->returnFail('亲属手机号不能相同！');
                }

                $this->model::startTrans();
                try {
                    $res = $this->model::saveOne($info);
                    if ( $res === false ) throw new \Exception('保存失败【10001】');

                    $this->model::commitTrans();

                    $user = $this->model::where('uid',$info['uid'])->find();
                    return $this->returnSuccess($user);
                } catch ( \Exception $e ) {
                    $this->model::rollbackTrans();
                    return $this->returnFail($e->getMessage());
                }
            }
        }
        return $this->returnFail('保存失败');
    }

    /**
     * 新增客户信息保存
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function saveNew()
    {
        $info = $this->request->post();
        if ( !empty($info) ) {
            $full_name = $info['full_name'] ?? '';
            if ( empty($full_name) ) return $this->returnFail('客户姓名必填');

            $mobile = $info['mobile'] ?? '';
            if ( empty($mobile) ) return $this->returnFail('客户手机号必填');

            ## 检查是否已存在
            $his = $this->model::where('mobile' , $mobile)->count();
            if ( $his > 0 ) return $this->returnFail('手机号关联的客户已存在！');

            $mate_mobile = $info['mate_mobile'] ?? '';
            if ( $mate_mobile ) {
                ## 检查是否已存在
                $his = $this->model::where('mate_mobile' , $mate_mobile)->whereOr('mate_mobile2' , $mate_mobile)->count();
                if ( $his > 0 ) return $this->returnFail('亲属手机号关联的客户已存在！');
            }

            $mate_mobile2 = $info['mate_mobile2'] ?? '';
            if ( $mate_mobile2 ) {
                ## 检查是否已存在
                $his = $this->model::where('mate_mobile' , $mate_mobile2)->whereOr('mate_mobile2' , $mate_mobile2)->count();
                if ( $his > 0 ) return $this->returnFail('亲属手机号关联的客户已存在！');
            }

            if ( $mate_mobile && $mate_mobile2 ) {
                if ( $mate_mobile == $mate_mobile2 ) return $this->returnFail('亲属手机号不能相同！');
            }

            $this->model::startTrans();
            try {
                $sales_admin_id = $this->model::calcSalesAdminId($this->uid);

                $newUser = [
                    'mobile' => $mobile,
                    'mate_mobile' => $mate_mobile,
                    'mate_mobile2' => $mate_mobile2,
                    'full_name' => $full_name,
                    'sales_admin_id' => $sales_admin_id,
                    'spread_suid' => $this->uid,
                    'remark' => $info['remark']??'',
                    'tour_perfer' => $info['tour_perfer']??'',
                    'tour_target' => $info['tour_target']??'',
                    'cus_from' => $info['cus_from']??'',
                    'wheregone' => $info['wheregone']??'',
                    'is_idcheck' => $info['idnumber'] ? 1 : 0
                ];
 
                $res = $this->model::create_new_user($newUser);
                if ( $res === false ) throw new \Exception('创建失败【10001】');

                if ( !empty($info['idnumber']) ) {
                    $res = M\user\UserIdcard::create([
                        'uid' => $res->uid,
                        'realname' => $full_name,
                        'idnumber' => $info['idnumber'],
                        'check_time' => date('Y-m-d H:i:s')
                    ]);
                    if ( $res === false ) throw new \Exception('创建失败【10002】');
                }
            
                $this->model::commitTrans();
                return $this->returnSuccess();
            } catch ( \Exception $e ) {
                $this->model::rollbackTrans();
                return $this->returnFail($e->getMessage());
            }
            
        }
        return $this->returnFail('保存失败');
    }
    

    /**
     * 客户跟进信息保存
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function saveProcesson()
    {
        $info = $this->request->post();

        $uid = $info['uid'] ?? 0;
        $content = $info['content'] ?? '';

        if ( !$uid || $content == '' ) return $this->returnFail('提交内容不能为空');

        ## 检查是否有权操作
        $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
        if ( $sales_admin_id > 0 ) {
            $cusUserAdminId = $this->model::where('uid',$uid)->value('sales_admin_id');
            if ( $sales_admin_id != $cusUserAdminId ) return $this->returnFail('无权操作');

            $this->model::startTrans();
            try {
                $processonDate = date('Y-m-d H:i:s');
                $record = [
                    'uid'               => (int)$uid,
                    'sales_admin_id'    => (int)$sales_admin_id,
                    'content'           => $content,
                    'ontime'            => $processonDate
                ];
                ## 保存跟进记录
                $res = M\CustomerProcesson::saveOne($record);
                if ( $res === false ) throw new \Exception('保存失败【10001】');

                ## 更新对应客户最后跟进时间
                $res = M\User::where('uid',$uid)->update(['last_processon_time' => $processonDate]);
                if ( $res === false ) throw new \Exception('保存失败【10002】');

                $this->model::commitTrans();
                return $this->returnSuccess();
            } catch ( \Exception $e ) {
                $this->model::rollbackTrans();
                return $this->returnFail($e->getMessage());
            }
        }
        
        return $this->returnFail('保存失败');
    }

    /**
     * 客户跟进信息列表
     */  
    public function processons()
    {
        $processons = [];
        ## 检查是否有权操作
        $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
        if ( $sales_admin_id > 0 ) {
            $filter = input();
            $filter['sales_admin_id'] = $sales_admin_id;
            $list = M\CustomerProcesson::getList($filter);
            if ( isset($list['data']) ) {
                $processons = $list['data'];
            }
        }

        return $this->returnSuccess($processons);
    }

    /**
     * [notices description]
     * @Author   FW
     * @DateTime 2024-08-26
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function notices()
    {
        $notices = [];
        ## 检查是否有权操作
        $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
        if ( $sales_admin_id > 0 ) {
            $filter = input();
            $filter['sales_admin_id'] = $sales_admin_id;
            $list = M\CustomerNotice::getList($filter);
            if ( isset($list['data']) ) {
                $notices = $list['data'];
            }
        }

        return $this->returnSuccess($notices);
    }

    /**
     * 提醒信息保存
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function saveNotice()
    {
        $info = $this->request->post();

        $uid     = $info['cus_uid'] ?? 0;
        $date    = $info['notice_date'] ?? '';
        $time    = $info['notice_time'] ?? '';
        $content = $info['notice_content'] ?? '';

        if ( !$content || !$date || !$time  ) return $this->returnFail('提交内容不能为空');

        ## 检查是否有权操作
        $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
        if ( $sales_admin_id > 0 ) {
            // $cusUserAdminId = $this->model::where('uid',$uid)->value('sales_admin_id');
            // if ( $sales_admin_id != $cusUserAdminId ) return $this->returnFail('无权操作');

            $this->model::startTrans();
            try {
                $record = [
                    'cus_uid'           => (int)$uid,
                    'sales_admin_id'    => (int)$sales_admin_id,
                    'uid'               => (int)$this->uid,
                    'notice_date'       => $date,
                    'notice_time'       => $time,
                    'notice_content'    => $content,
                    'process_time'      => 0
                ];
                ## 保存跟进记录
                $res = M\CustomerNotice::saveOne($record);
                if ( $res === false ) throw new \Exception('保存失败【10001】');

                $this->model::commitTrans();
                return $this->returnSuccess();
            } catch ( \Exception $e ) {
                $this->model::rollbackTrans();
                return $this->returnFail($e->getMessage());
            }
        }
        
        return $this->returnFail('保存失败');
    }

    /**
     * 添加、修改客户身份证信息
     * @Author   FW
     * @DateTime 2024-12-23
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function saveIdcard()
    {
        $info = $this->request->post();
        if ( !empty($info) ) {
            if ( empty($info['uid']) ) return $this->returnFail('保存失败[10001]');
            if ( empty($info['realname']) ) return $this->returnFail('真实姓名必填');
            if ( empty($info['idnumber']) ) return $this->returnFail('身份证号必填');

            M\user\UserIdcard::startTrans();
            try {
                $info['check_time'] = date('Y-m-d H:i:s');
                $res = M\user\UserIdcard::saveOne($info);
                if ( $res === false ) throw new \Exception('保存失败【10001】');

                ## 更新用户实名及生日
                $birthday = idnumber2birthday($info['idnumber']);
                $res = M\User::where('uid',$info['uid'])->update(['is_idcheck' => 1,'full_name' => $info['realname'], 'birthday' => $birthday ]);
                if ( $res === false ) throw new \Exception('保存失败【10002】');

                M\user\UserIdcard::commitTrans();
                return $this->returnSuccess();
            } catch ( \Exception $e ) {
                M\user\UserIdcard::rollbackTrans();
                return $this->returnFail($e->getMessage());
            }
        }

        M\user\UserIdcard::rollbackTrans();
        return $this->returnFail('保存失败');
    }
}//Class End